index_app.controller("main", function ($scope,$http,$timeout) {
    $('#myModal').modal('hide');
    $('#myModalPay').modal('hide');
    $('#fixedModal').modal('hide');
    $scope.isAdd = true;
    $scope.todayTime = new Date();
    loadSite();
    loadRev();
    insertSiteInfo(getDateString($scope.todayTime));

    $scope.payMethod=['现金','支付宝','微信'];
    $scope.cardTypeLst = ['身份证','驾驶证','学生证'];
    $scope.show_day=['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
    console.log($scope.show_day[$scope.todayTime.getDay()]);

    //结束时间失去焦点时间
    $scope.endD =function(){
          var d1 = new Date("1111/1/1 "+$("#startTime").val()+":00");
          var d2 = new Date("1111/1/1 "+$("#endTime").val()+":00");
          $scope.day = $scope.todayTime.getDay();
          if($("#startTime").val() >= "9:00" && $("#endTime").val() <= "17:00" &&  $scope.day >=1 && $scope.day <= 5){
                //console.log("50元/小时");
                $scope.tollStandard = "50元/小时";
                $scope.tollPrice = 50;
          } else if($("#startTime").val() >= "17:00" && $("#endTime").val() <= "22:00" &&  $scope.day >=1 && $scope.day <= 5){
                //console.log("70元/小时");
                $scope.tollStandard = "70元/小时";
                $scope.tollPrice = 70;
          } else{
                //console.log("startTime 70元/小时");
                $scope.tollStandard = "70元/小时";
                $scope.tollPrice = 70;
          }
    }

     $http.post("stmUsr/selectAll").then(function(response){
        	//数据源
        	$scope.stmUsrList = response.data;
      });
      //今天点击时间
    $scope.todayNow = function(){
        $scope.isAdd = true;
        $scope.todayTime = new Date();
        loadSite();
        loadRev();
        insertSiteInfo(getDateString($scope.todayTime));
    }

    //通过时间查询事件
    $scope.searchTime = function(){
        $scope.today = new Date();
        $scope.todayTime = $scope.startDate;
          $scope.differDay = ($scope.today.getTime() -  new Date($scope.todayTime).getTime());
                 $scope.tollStandard = "";
                 $scope.tollPrice = 0;
                $scope.isToday = likeDay($scope.today,new Date($scope.todayTime));
                if($scope.isToday == 1){
                     $scope.isAdd = true;
                } else {
                    if($scope.differDay > 0){
                         $scope.isAdd = false;
                    } else {
                        $scope.isAdd = true;
                    }
                }

        $http.post("siteRev/selectByScheduledDate?scheduledDate="+$scope.todayTime).then(function(response){
                            $scope.siteRevList = response.data;
                            $scope.siteTypeList = $scope.siteRevList[0].typeSeq;
                            $scope.siteTime = $scope.siteTypeList[0].timeSeq;
                   });
        loadRev();
        insertSiteInfo($scope.todayTime);
    }

    //日期格式化
    function getDateString(dateTime){
        $scope.year = dateTime.getFullYear();
        $scope.month = (dateTime.getMonth())+1;
        $scope.day = dateTime.getDate();
        return $scope.year+"-"+$scope.month+"-"+$scope.day;
    }

    function likeDay(nowDay,otherDay){
        if(nowDay.getFullYear() == otherDay.getFullYear() && nowDay.getMonth() == otherDay.getMonth() && nowDay.getDate() == otherDay.getDate()){
            return 1;
        } else {
            return 0;
        }
    }
    //前一天
    $scope.prwDay = function(){
        $scope.isAdd = false;
        $scope.today = new Date();
        $scope.todayTime = new Date($scope.todayTime.getTime() - (1000 * 60 * 60 * 24));
        $scope.differDay = ($scope.today.getTime() - $scope.todayTime.getTime());
         $scope.tollStandard = "";
         $scope.tollPrice = 0;
        $scope.isToday = likeDay($scope.today,$scope.todayTime);
        if($scope.isToday == 1){
             $scope.isAdd = true;
        } else {
            if($scope.differDay > 0){
                  $scope.isAdd = false;
             } else {
                 $scope.isAdd = true;
             }
        }

        loadSite();
        loadRev();
    }

    //下一天点击时间
    $scope.nextDay = function(){
     $scope.today = new Date();
        $scope.todayTime = new Date($scope.todayTime.getTime() + (1000 * 60 * 60 * 24));
        $scope.differDay = ($scope.today.getTime() - $scope.todayTime.getTime());
        $scope.tollStandard = "";
        $scope.tollPrice = 0;
        $scope.isToday = likeDay($scope.today,$scope.todayTime);
          if($scope.isToday == 1){
                $scope.isAdd = true;
           } else {
                if($scope.differDay > 0){
                 $scope.isAdd = false;
                } else {
                    $scope.isAdd = true;
                }
          }
         loadSite();
         loadRev();
         insertSiteInfo(getDateString($scope.todayTime));
    }

    function loadSite(){
          $http.post("siteRev/selectByScheduledDate?scheduledDate="+getDateString($scope.todayTime)).then(function(response){
                     $scope.siteRevList = response.data;
                     $scope.siteTypeList = $scope.siteRevList[0].typeSeq;
                     $scope.siteTime = $scope.siteTypeList[0].timeSeq;
            });
    }
    function loadRev(){
            $scope.timeArry5 = new Array();
         $timeout(function(){
            $scope.timeCount = 0;
                for(var i = 0;i<$scope.siteRevList.length;i++){
                        $scope.placedKey = $scope.siteRevList[i].placeKey.placeKey;
                        $scope.timedKey = $scope.siteRevList[i].timeKey.timeKey;
                        if($scope.siteRevList[i].state == 1){
                            //获取dom对象，并且进行addclass操作
                            angular.element(document).ready(function () {
                                var radio = angular.element("#site_"+$scope.placedKey+"_"+$scope.timedKey)[0];
                                 angular.element(radio).removeClass("bagGreen");
                                angular.element(radio).addClass("bagColored");
                            });
                            $scope.date1 = new Date($scope.siteRevList[i].scheduledDate).getTime();
                             if($scope.isAdd == true){
                                $scope.unBtn = "<button onclick='unsubscribe("+$scope.date1+","+$scope.siteRevList[i].placeKey.placeKey+","+$scope.siteRevList[i].vipNum+",1)' >退订</button>";
                             } else {
                                $scope.unBtn = "";
                             }
                            $("#site_"+$scope.placedKey+"_"+$scope.timedKey).html($scope.siteRevList[i].vipName+"  已结算  "+ $scope.unBtn);
                        } else if($scope.siteRevList[i].state == 4){
                               angular.element(document).ready(function () {
                                   var radio = angular.element("#site_"+$scope.placedKey+"_"+$scope.timedKey)[0];
                                   angular.element(radio).removeClass("bagGreen");
                                   angular.element(radio).addClass("bagYellow");
                             });
                             $scope.date = new Date($scope.siteRevList[i].scheduledDate).getTime();
                              $scope.unBtn = "<button onclick='unsubscribe("+$scope.date+","+$scope.siteRevList[i].placeKey.placeKey+","+$scope.siteRevList[i].vipNum+",4)' >退订</button>";
                             $("#site_"+$scope.placedKey+"_"+$scope.timedKey).html($scope.siteRevList[i].vipName+"未付款  <button onclick='payment("+$scope.siteRevList[i].timePrice+","+$scope.siteRevList[i].priceTotal+","+$scope.date+","+$scope.siteRevList[i].placeKey.placeKey+","+$scope.siteRevList[i].vipNum+","+$scope.siteRevList[i].phone+",\""+$scope.siteRevList[i].vipName+"\",4)' >付款</button>"+$scope.unBtn);
                        }else if($scope.siteRevList[i].state == 5){
                            angular.element(document).ready(function () {
                                var radio = angular.element("#site_"+$scope.placedKey+"_"+$scope.timedKey)[0];
                                angular.element(radio).removeClass("bagGreen");
                                angular.element(radio).addClass("bagYellow");
                          });
                          /* $scope.timeArry5.push($scope.siteRevList[i].timeKey.timeDate);
                           console.log($scope.timeArry5);
                           $scope.scheDay = new Date($scope.siteRevList[i].scheduledDate).getDay();*/
                           $scope.date = new Date($scope.siteRevList[i].scheduledDate).getTime();
                           $scope.unBtn = "<button onclick='unsubscribe("+$scope.date+","+$scope.siteRevList[i].placeKey.placeKey+","+$scope.siteRevList[i].vipNum+",5)' >退订</button>";
                           //$scope.onePrice = timeCountFun($scope.timeArry5[0],$scope.timeArry5[1],$scope.scheDay);

                           //$("#original").val($scope.siteRevList[i].priceTotal);
                           $("#site_"+$scope.placedKey+"_"+$scope.timedKey).html($scope.siteRevList[i].vipName+"未付款  <button onclick='payment("+$scope.siteRevList[i].timePrice+","+$scope.siteRevList[i].priceTotal+","+$scope.date+","+$scope.siteRevList[i].placeKey.placeKey+","+$scope.siteRevList[i].vipNum+","+$scope.siteRevList[i].phone+",\""+$scope.siteRevList[i].vipName+"\",5)' >付款</button>"+$scope.unBtn);

                         }

                    }
             },900);
    }

    $scope.reserve = function(site){
         $('#myModal').modal('show');
         $scope.siteInfo = site;
    }

    function timeCountFun(startTime,endTime,nowDay){
      if(startTime >= "9:00" &&endTime <= "17:00" &&  nowDay >=1 && nowDay <= 5){
             return 50;
       } else if(startTime >= "17:00" && endTime <= "22:00" && nowDay >=1 && nowDay <= 5){
             return 70;
       } else{
             return 70;
       }
    }

    function insertSiteInfo(time){
         $scope.siteInfoUpdate = function(siteInfo){
                $scope.plyKey = siteInfo.placeKey;
                siteInfo.scheduledDate = time;
                console.log($scope.plyKey);
                var d1 = new Date("1111/1/1 "+$("#startTime").val()+":00");
                var d2 = new Date("1111/1/1 "+$("#endTime").val()+":00");
                $scope.timeArry = new Array();
                $scope.timeArry.push($("#startTime").val());
                $scope.timeArry.push($("#endTime").val());
                if(d2 - d1 < 0){
                    alert("请填写正确时间");
                } else {
                   var gap = Math.abs(d1-d2)/1000/60/60;
                   siteInfo.priceTotal = $scope.tollPrice * gap;
                   console.log(siteInfo.priceTotal);
                   console.log($scope.tollPrice);
                   //获取两个时之间相差的时分
                   for(var  i =0;i<(gap*2)-1;i++){
                      d1.setMinutes(d1.getMinutes()+30);
                      if(d1.getMinutes() == 0){
                        $scope.timePreid = d1.getHours()+":00";
                        $scope.timeArry.push($scope.timePreid);
                      } else {
                         $scope.timePreid = d1.getHours() +":"+d1.getMinutes();
                         $scope.timeArry.push($scope.timePreid);
                      }
                   }
                    console.log($scope.timeArry);
                           siteInfo.placeKey = null;
                           siteInfo.typeSeq = null;
                           siteInfo.timePrice = siteInfo.priceTotal;
                            $http({
                           					method  : 'POST',
                           					url     : 'siteRev/insertAll?revTime='+ $scope.timeArry+"&plyKey="+$scope.plyKey,
                           					data:siteInfo
                           				}).success(function(data) {
                                               if(data==1){
                                                   $scope.title = '<h4 class="easyDialog_title" id="easyDialogTitle"><i class="icon-ok green"></i> <a href="javascript:void(0)" title="关闭窗口" class="close_btn" id="closeBtn">&times;</a>保存</h4>';
                           						//保存成功内容
                           						$scope.toolTip = "保存成功";
                           						toolTipDialog();
                           						$('#myModal').modal('hide');
                           						 loadSite();
                                                 loadRev();
                           					    //window.location.href="#sales";
                                               } else {
                                                     $scope.title = "保存";
                                                     $scope.toolTip = "保存失败,预定时间段已经被预定";
                                                      toolTipDialog();
                                                      $('#myModal').modal('hide');
                                               }
                           				});
                }
            }
    }

    $scope.payMentUpdate = function(payMentInfo){
        if($("#state").val() == '4'){
            payMentInfo.priceTotal = $("#timePrice").val();
        }
         payMentInfo.timePrice = $("#timePrice").val();
         console.log(payMentInfo.timePrice);
         payMentInfo.phone = $("#phone1").val();
         payMentInfo.vipName = $("#vipPayName").val();
         payMentInfo.vipNum = $("#vipPayNum").val();

         payMentInfo.scheduledDate = $("#scheduledDate").val();
         payMentInfo.state = $("#state").val();

     $http({
                method  : 'POST',
                url     : 'siteRev/updatePayData?plyKey='+$("#placeKey").val(),
                data:payMentInfo
            }).success(function(data) {
                 if(data==1){
                     $scope.title = '<h4 class="easyDialog_title" id="easyDialogTitle"><i class="icon-ok green"></i> <a href="javascript:void(0)" title="关闭窗口" class="close_btn" id="closeBtn">&times;</a>保存</h4>';
                    //保存成功内容
                    $scope.toolTip = "保存成功";
                    toolTipDialog();
                    $('#myModalPay').modal('hide');
                     loadSite();
                   loadRev();
                    //window.location.href="#sales";
                 } else {
                       $scope.title = "保存";
                       $scope.toolTip = "保存失败,预定时间段已经被预定";
                        toolTipDialog();
                        $('#myModalPay').modal('hide');
                 }
            });
    }

     function toolTipDialog(){
            		easyDialog.open({
            			container : {
            				header : $scope.title,
            				content : $scope.toolTip,
            				yesFn : $scope.toolFn,
            				noFn : false
            			},
            			fixed : false
            		});
            	}
            	//弹窗中确定按钮事件
            	$scope.toolFn = function(){
            		return true;
            	}
     $scope.fixedSite = function(){
         $('#fixedModal').modal('show');
     }

     $scope.checkPhone = function(){
        console.log($scope.fixedSiteInfo.phone);
        if($scope.fixedSiteInfo.phone.length != 11){
            alert("输入的手机号有误，请重新输入");
        }
     }

     $scope.checkVip = function(vipNum){
        $http.post("menberInfo/selectByVipNum?vipNum="+vipNum).then(function(response){
                $scope.vipMsg = response.data;
                if($scope.vipMsg == ""){
                    alert("输入卡号有误，请重新输入");
                }
        });
     }

   //固定场地结束时间失去焦点时间
       $scope.fixedEndTime =function(){
             var d1 = new Date("1111/1/1 "+$("#startFixedTime").val()+":00");
             var d2 = new Date("1111/1/1 "+$("#endFixedTime").val()+":00");
             $scope.day = $scope.todayTime.getDay();
             if($("#startFixedTime").val() >= "9:00" && $("#endFixedTime").val() <= "17:00" &&  $scope.day >=1 && $scope.day <= 5){
                   //console.log("50元/小时");
                   $scope.totalFixedStandard = "50元/小时";
                   $scope.tollFixedPrice = 50;
             } else if($("#startFixedTime").val() >= "17:00" && $("#endFixedTime").val() <= "22:00" &&  $scope.day >=1 && $scope.day <= 5){
                   //console.log("70元/小时");
                   $scope.totalFixedStandard = "70元/小时";
                   $scope.tollFixedPrice = 70;
             } else{
                   //console.log("startTime 70元/小时");
                   $scope.totalFixedStandard = "70元/小时";
                   $scope.tollFixedPrice = 70;
             }
       }


     $scope.fixedUpdate = function(fixedSiteInfo){
          $scope.plyFixedKey = fixedSiteInfo.placeKey;
          var d3 = new Date("1111/1/1 "+$("#startFixedTime").val()+":00");
          var d4 = new Date("1111/1/1 "+$("#endFixedTime").val()+":00");
          $scope.timeFixedArry = new Array();
          $scope.timeFixedArry.push($("#startFixedTime").val());
          $scope.timeFixedArry.push($("#endFixedTime").val());
          $scope.differFixedDay = (new Date($scope.endFixedDate).getTime() -  new Date($scope.startFixedDate).getTime());

           $scope.differAllDay = Math.floor($scope.differFixedDay/(24*3600*1000));
            console.log($scope.differAllDay);
           if(d4 - d3 < 0){
             alert("请填写正确时间段");
           } else if(!checkEndTime($scope.startFixedDate,$scope.endFixedDate)){
              $scope.title = "警告";
              $scope.toolTip = "开始时间小于结束时间，请重新选择";
              toolTipDialog();
           }
           else {
              var gap = Math.abs(d3-d4)/1000/60/60;
                 fixedSiteInfo.priceTotal = $scope.tollFixedPrice * gap *  ($scope.differAllDay*1+1);
                 fixedSiteInfo.timePrice = $scope.tollFixedPrice * gap
                 console.log(fixedSiteInfo.priceTotal);
               //获取两个时之间相差的时分
                 for(var  i =0;i<(gap*2)-1;i++){
                    d3.setMinutes(d3.getMinutes()+30);
                    if(d3.getMinutes() == 0){
                      $scope.timeFixedPreid = d3.getHours()+":00";
                      $scope.timeFixedArry.push($scope.timeFixedPreid);
                    } else {
                       $scope.timeFixedPreid = d3.getHours() +":"+d3.getMinutes();
                       $scope.timeFixedArry.push($scope.timeFixedPreid);
                    }
                 }
            fixedSiteInfo.placeKey = null;
            fixedSiteInfo.typeSeq = null;
             $http({
                    method  : 'POST',
                    url     : 'siteRev/fixedSite?revTime='+ $scope.timeFixedArry+"&plyKey="+ $scope.plyFixedKey+"&startFixedDate="+$scope.startFixedDate+"&endFixedDate="+$scope.endFixedDate,
                    data:fixedSiteInfo
                }).success(function(data) {
                       if(data==1){
                           $scope.title = '<h4 class="easyDialog_title" id="easyDialogTitle"><i class="icon-ok green"></i> <a href="javascript:void(0)" title="关闭窗口" class="close_btn" id="closeBtn">&times;</a>保存</h4>';
                        //保存成功内容
                        $scope.toolTip = "保存成功";
                        toolTipDialog();
                        $('#fixedModal').modal('hide');
                         loadSite();
                         loadRev();
                       } else {
                             $scope.title = "保存";
                             $scope.toolTip = "保存失败,预定时间段已经被预定";
                              toolTipDialog();
                              $('#fixedModal').modal('hide');
                       }
                });
           }
     }

     function checkEndTime(startTime,endTime){
             $scope.start=new Date(startTime.replace("-", "/").replace("-", "/"));
             $scope.end=new Date(endTime.replace("-", "/").replace("-", "/"));

             if($scope.end < $scope.start){
                 return false;
             }
             return true;
         }

});
function payment(timePrice,priceTotal,scheduledDate,placeKey,vipNum,phone,vipName,state){
        $('#myModalPay').modal('show');
        $("#timePrice").val(timePrice);
        $("#vipPayNum").val(vipNum);
        $("#placeKey").val(placeKey);
        $("#phone1").val(phone);
        $("#vipPayName").val(vipName);
        $("#scheduledDate").val(scheduledDate);
        $("#state").val(state);
}


 function getDateString(dateTime){
        var year = dateTime.getFullYear();
        var month = (dateTime.getMonth())+1;
        var day = dateTime.getDate();
        return year+"-"+month+"-"+day;
}

function unsubscribe(scheduledDate,placeKey,vipNum,state){
        var time = getDateString(new Date(scheduledDate));
        if(confirm("是否退订")){
           $.ajax({
              url: "siteRev/unsubscribe?scheduledDate="+time+"&plyKey="+placeKey+"&vipNum="+vipNum+"&state="+state,
              type: 'post',
              success: function (data, status) {
                console.log(data)
                if(data == 1){
                    alert("退订成功");
                    window.location.href="#index";
                } else {
                    alert("退订失败");
                }
              },
              fail: function (err, status) {
                console.log(err)
              }
            })
        }
        console.log(getDateString(new Date(scheduledDate)));
        console.log(placeKey);
        console.log(vipNum);
}
